﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommonTools;
using System.Data;
using shop.Model;
using Newtonsoft.Json.Linq;

namespace shop.Bll.Logi
{
    public class QueryLogisticsBll
    {

        /// <summary> 从excel读取快递信息 </summary>
        //public IEnumerable<dynamic> FromExcel(string excelFile, out string err)
        //{
            //if (string.IsNullOrEmpty(excelFile) || File.Exists(excelFile) == false)
            //{
            //    err = "文件未找到!";
            //    return null;
            //}

            //var dt = ExcelHelper.Import(excelFile);

            //if (dt == null)
            //{
            //    err = null;
            //    return null;
            //}

            ////猪猪快递云
            ////快递单号	快递公司	揽收时间	最新时间	时效	发出至今	最新至今	条数	最后1条物流信息	物流状态	查询时间	完整物流信息	订单编号	倒数第2条物流信息	第1条物流信息	任务备注


            //var list = dt.AsEnumerable()
            //    .Select(a => new ExpressInfo()
            //    {
            //        id = 0,
            //        LogisticCode = a.Field<string>(0),
            //        ExpressCompany = a.Field<string>(1),
            //        DeliveryTime = a.Field<DateTime?>(2),
            //        LastUpdateTime = a.Field<DateTime?>(3),
            //        Timeliness = a.Field<string>(4),
            //        SinceSent = a.Field<string>(5),
            //        SinceLastUpdate = a.Field<string>(6),
            //        ItemsCount = a.Field<int?>(7) ?? 0,
            //        LastLogisticsUpdate = a.Field<string>(8),
            //        LogisticsStatus = a.Field<string>(9),
            //        QueryTime = a.Field<DateTime?>(10),
            //        FullLogisticsInfo = a.Field<string>(11),
            //        TradeNo = a.Field<string>(12),
            //        SecondLastLogisticsUpdate = a.Field<string>(13),
            //        FirstLogisticsUpdate = a.Field<string>(14),
            //        TaskRemarks = a.Field<string>(15),
            //    })
            //    .ToList();


            //err = null;
            //return list;
        //}


        /// <summary> 订单与物料信息匹配 </summary>
        public List<TradeLogisticsData> TradeMatchExpress(IEnumerable<tradeData> trades, IEnumerable<LogiTrace> expresses)
        {
            var list = new List<TradeLogisticsData>();

            var map = MyMapper.GetMapper();

            //
            foreach (var item in trades)
            {
                var temp = map.Map<TradeLogisticsData>(item);
                list.Add(temp);

                if (string.IsNullOrEmpty(item.logistics_no))
                {
                    continue;
                }

                var find = expresses.FirstOrDefault(a => a.logistics_no == item.logistics_no && a.LogisticsCompany == item.logistics_name);
                if (find != null)
                {
                    if (find.ItemsCount ==0)
                    {
                        temp.LogisticsStatus = "0信息";
                    }
                    else
                    {
                        temp.LogisticsStatus = "正常";
                    }
                }
                else
                {
                    temp.LogisticsStatus = "无快递信息";
                }
            }

            return list;
        }

        /// <summary> 查询物流公司 </summary>
        public async Task<IEnumerable< logistics>> QuerylogisticsCompany()
        {
            var res = await new WdtApi("logistics.php")
            .Post<shop.Model.logisticsResult>();

            foreach (var item in res.logistics_list.Where(a=> a.is_disabled == 0))
            {
                if (_logi.Value.TryGetValue(item.logistics_type, out var logistics))
                {
                    item.LogiCompany= logistics;
                }
            }

            return res.logistics_list;
        }


        /// <summary> 快递公司发来的张单, 检查需要预付的快递 </summary>
        public IEnumerable<LogiTrace> ReviewLogistics(IEnumerable<tradeData> trades, IEnumerable<LogiTrace> items)
        {
            return null;

            //var list = new List<tradeExpressData>();

            //var map = Model.MapperProfile.GetMapper();

            ////
            //foreach (var item in trades)
            //{
            //    var temp = map.Map<tradeExpressData>(item);
            //    list.Add(temp);

            //    if (string.IsNullOrEmpty(item.logistics_no))
            //    {
            //        continue;
            //    }

            //    var find = expresses.FirstOrDefault(a => a.LogisticCode == item.logistics_no && a.ExpressCompany == item.logistics_name);
            //    if (find != null)
            //    {
            //        if (find.ItemsCount == 0)
            //        {
            //            temp.ExpressStatus = "0信息";
            //        }
            //        else
            //        {
            //            temp.ExpressStatus = "正常";
            //        }
            //    }
            //    else
            //    {
            //        temp.ExpressStatus = "无快递信息";
            //    }
            //}

            //return list;
        }



        /// <summary> 从旺店通同步数据 </summary>
        public async Task<int> SyncFromWdt()
        {
            int count = 0;

            while (true)
            {
                //分3步

                //1. 查询
                var res = await new WdtApi("logistics_sync_query.php")
                  .AddParam("limit", "100")
                  .Post<shop.Model.logistics_sync_queryResult>();

                if (res?.trades == null || res?.trades?.Count() == 0)
                {
                    //无数据, 跳出循环
                    break ;
                }

                count += res.trades.Count();

                //2. 写入到数据库

                await DB.FSql.InsertOrUpdate<logistics_sync_queryResultItem>()
                    .SetSource(res.trades)
                    .ExecuteSqlBulkCopyAsync();


                //3. 写入服务器完成后, 将通过结果回写到旺店通服务端

                var logistics_list = res.trades
                    .Select(a => new logistics_sync_ackPara()
                    {
                        rec_id = a.rec_id,
                        message = "",
                        status = a.sync_status,
                    })
                    .ToArray();

                var prjson = JObject.FromObject(logistics_list).ToString();


                var act = await new WdtApi("logistics_sync_ack.php")
                    .AddParam("logistics_list", prjson)
                    .Post();


            }

            return count;

            //https://open.wangdian.cn/qyb/open/apidoc/doc?path=logistics_sync_query.php

        }


        /// <summary> 查询销售出库单 </summary>
        public async Task<stockout_order_query_tradeResult> stockout_order_query_trade(DateTime begin, DateTime end, int page_no)
        {
            if (begin == end)
            {
                begin = end.AddMinutes(-10);
            }

            var res = await new WdtApi("stockout_order_query_trade.php")
               .AddParam("start_time", begin.ToString("yyyy-MM-dd HH:mm:ss"))
               .AddParam("end_time", end.ToString("yyyy-MM-dd HH:mm:ss"))
               .AddParam("page_size", "100")
               .AddParam("page_no", page_no.ToString())
               .Post<shop.Model.stockout_order_query_tradeResult>();

            //if (res?.stockout_list == null || res?.stockout_list?.Count() == 0)
            //{
            //    //无数据, 跳出循环
            //    return null;
            //}

            return res;

        }

        /// <summary> 同步物流公司 </summary>
        public async Task SyncLogisticsCompany()
        {
            var  res = await QuerylogisticsCompany();

            if (res?.Any() == true)
            {
                await DB.FSql.Update<logistics>()
                    .Set(a => a.isdel, true)
                    .ExecuteAffrowsAsync();

                foreach (var item in res)
                {
                    item.isdel = false;
                }

                await DB.FSql.InsertOrUpdate<logistics>()
                    .SetSource(res)
                    .IgnoreColumns(nameof(logistics.Name))
                    .ExecuteAffrowsAsync();

            }
        }



        private Lazy<Dictionary<int, string>> _logi = new Lazy<Dictionary<int, string>>(() =>
        {
            return new Dictionary<int, string>()
            {
                {1, "无单号物流"},
{2, "中国邮政平邮"},
{3, "EMS"},
{4, "圆通速递"},
{5, "中通快递"},
{6, "申通快递"},
{7, "全峰快递"},
{8, "顺丰速运"},
{9, "韵达快递"},
{10,    "汇通快运（百世汇通）"},
{11,    "中铁快运"},
{12,    "中远"},
{13,    "龙邦速递"},
{14,    "快捷速递"},
{15,    "全日通快递"},
{16,    "海航天天快递"},
{17,    "发网"},
{18,    "联昊通"},
{19,    "宅急送"},
{20,    "百世物流"},
{21,    "联邦快递"},
{22,    "德邦物流"},
{23,    "华强物流"},
{24,    "星辰急便"},
{25,    "亚风"},
{26,    "长宇"},
{27,    "大田"},
{28,    "长发"},
{29,    "安得"},
{30,    "CCES"},
{31,    "东方汇"},
{32,    "首业"},
{33,    "远长"},
{34,    "新邦物流"},
{35,    "优速物流"},
{36,    "港中能达"},
{37,    "全一快递"},
{38,    "黑猫宅急便"},
{39,    "浙江ABC"},
{40,    "杭州爱彼西"},
{41,    "四川快捷"},
{42,    "贝业新兄弟"},
{45,    "EMS经济快递"},
{46,    "飞远配送"},
{47,    "尚橙物流"},
{48,    "广东EMS"},
{49,    "城市100"},
{50,    "汇强快递"},
{51,    "邮政国内小包"},
{52,    "国通快递"},
{53,    "E速宝"},
{54,    "同城快递"},
{55,    "北京EMS"},
{56,    "佳吉快递"},
{57,    "凡宇速递"},
{58,    "天地华宇"},
{59,    "居无忧"},
{60,    "美国速递"},
{70,    "派易国际物流77"},
{71,    "RUSTON"},
{72,    "速尔"},
{73,    "信丰物流"},
{74,    "燕文北京"},
{75,    "燕文广州"},
{76,    "燕文国际"},
{77,    "燕文上海"},
{78,    "燕文深圳"},
{79,    "燕文义乌"},
{80,    "合众阳晟"},
{81,    "ZTOGZ"},
{82,    "ZTOSH"},
{83,    "保宏物流"},
{84,    "增益速递"},
{85,    "贝海国际速递"},
{86,    "如风达配送"},
{87,    "安能快递"},
{88,    "德邦快递"},
{89,    "菜鸟智选物流"},
{90,    "菜鸟配送"},
{91,    "跨越速运"},
{92,    "百世快运"},
{93,    "D速物流"},
{94,    "德邦快运"},
{95,    "安能快运"},
{96,    "壹米滴答"},
{97,    "韵达快运"},
{98,    "品骏（JITX）"},
{99,    "圆通（JITX）"},
{100,   "圆通承诺达"},
{101,   "品骏快递"},
{102,   "芝麻开门"},
{103,   "京东大件物流"},
{104,   "苏宁快递"},
{105,   "蜂鸟配送"},
{106,   "顺丰快运"},
{107,   "京东纯配"},
{108,   "极兔速递"},
{109,   "众邮快递"},
{201,   "九曳供应链"},
{1307,  "顺丰同城配"},
{1308,  "菜鸟落地配-万象"},
{1309,  "青岛日日顺"},
{1311,  "京邦达"},
{2000,  "其他"},
{2005,  "成都东骏快捷物流有限公司"},
{2006,  "小家电-陕西黄马甲"},
{2036,  "亚马逊"},
{2039,  "八达通物流"},
{2087,  "九曳鲜配"},
{2074,  "韵达国际"},
{2075,  "天天国际"},
{2076,  "递四方"},
{2077,  "中远E环球"},
{2078,  "秀驿物流"},
{2079,  "优邦速运"},
{2080,  "VoyageOne"},
{2081,  "UEQ"},
{2082,  "斑马物联网"},
{2083,  "卓志速运"},
{2084,  "申通国际"},
{2085,  "威时沛运"},
{2088,  "香港邮政"},
{2089,  "中通国际"},
{2090,  "广东EMS跨境易"},
{2093,  "日本邮政"},
{2094,  "贝海国际"},
{2095,  "百世国际"},
{2110,  "中通快运"},
{2115,  "圆通国际（海外G面单）"},
{2116,  "高捷跨境快运"},
{2117,  "易客满国际物流"},
{2128,  "京广速递"},
{2124,  "EWE GLOBAL"},
{2127,  "顺心捷达"},
{2129,  "圆通国际(海外会员版)"},
{2131,  "丰网速运"},
{2132,  "淘特官方物流"},
{2133,  "1688官方快递"},
{2134,  "1688官方快运"},
{2135,  "速通物流"},
{2136,  "抖店BIC送货"},
{2137,  "韵达同城"},
{2138,  "菜鸟裹裹同城特快"},
{2139,  "加运美"},
{2140,  "平安达腾飞"},
{2141,  "丹鸟快递"},
{2143,  "快弟来了"},
{2146,  "京东快递(无店铺)"},
{2154,  "邮政电商标快"},
{3017,  "安迅物流"},
            };
        });

    }
}
